let activeUrl = '';

// 监听请求并修改地址
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if (activeUrl) {
            try {
                const originalUrl = new URL(details.url);
                const newUrl = new URL(activeUrl + originalUrl.pathname + originalUrl.search);
                return { redirectUrl: newUrl.toString() };
            } catch (error) {
                console.error('URL 解析错误:', error);
                return { cancel: false };
            }
        }
        return { cancel: false };
    },
    { urls: ['<all_urls>'] },
    ['blocking']
);

// 初始化时加载保存的地址并设置第一个为活动地址
chrome.storage.local.get('requestUrls', function(data) {
    const urls = data.requestUrls || {};
    for (const name in urls) {
        activeUrl = urls[name];
        break;
    }
});

// 监听来自 popup 的消息，切换活动地址
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'setActiveUrl') {
        activeUrl = request.url;
        sendResponse({ success: true });
    }
    return true;
});